package com.star.mall.utils;

import cn.hutool.core.lang.Assert;
import com.star.mall.model.UserDetail;
import com.star.mall.persistence.entity.User;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 上下文工具类
 * @author StarQ
 * @since 2021-04-21
 */
public class ContextUtil {

    public static UserDetail getCurrentUser() {
        return getCurrentUser((authentication) -> {
            Assert.notNull(authentication, "登录用户不能为空");
            return null;
        });
    }

    public static UserDetail getCurrentUser(Function<Authentication, UserDetail> supplier) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication instanceof AnonymousAuthenticationToken) {
            return supplier.apply(authentication);
        }
        Object principal = authentication.getPrincipal();
        return (UserDetail) principal;
    }

    public static String getCurrentUserId() {
        UserDetail userDetail = getCurrentUser();
        return userDetail.getId();
    }


}
